<?php

namespace App\Http\Controllers\OpenShop\Merchant;

use App\Enums\Workflow\WorkflowEnum;
use App\Http\Controllers\BaseController;
use App\Models\Workflow\WorkflowOrderLogModel;
use App\Models\Workflow\WorkflowOrderModel;
use App\Models\Workflow\WorkflowOrderNodeModel;
use App\Service\BaseService;
use App\Service\Cruise\Mission\RenewInputService;
use App\Service\Renew\RenewService;
use Illuminate\Http\Request;

class RenewController extends BaseController
{
    public function inputInfo(Request $request)
    {
        $workflowNo = $request->get('workflowNo');
        $userId     = getRmsUserId();

        list($workflowOrder, $workflowNode) = RenewService::getWorkflow($workflowNo);

        $data = [
            'workflow' => [
                'id'         => $workflowOrder->id,
                'status'     => $workflowOrder->status,
                'statusText' => WorkflowOrderModel::STATUS_TEXT[$workflowOrder->status] ?? '',
            ],
            'logs'     => (new WorkflowOrderLogModel)->merchantLogs($workflowOrder->id),
            'projects' => (new RenewInputService($workflowNode->cruiseOrderId, $userId))
                ->setWorkflowOrder($workflowOrder)
                ->getInputObjectFill(),
        ];

        return $this->success($data);
    }

    public function inputUpdate(Request $request)
    {
        $workflowNo = $request->get('workflowNo');
        $field      = (string)$request->get('field');
        $value      = $request->get('value');
        $userId     = getRmsUserId();

        list($workflowOrder, $workflowNode) = RenewService::getWorkflow($workflowNo);

        (new RenewInputService($workflowNode->cruiseOrderId, $userId))
            ->setWorkflowOrder($workflowOrder)
            ->checkSubmit()
            ->saveUserContentJson($field, $value, []);

        return $this->success();
    }

    public function inputSubmit(Request $request)
    {
        $workflowNo = $request->get('workflowNo');
        $userId = getRmsUserId();

        list($workflowOrder, $workflowNode) = RenewService::getWorkflow($workflowNo);

        (new RenewInputService($workflowNode->cruiseOrderId, $userId))
            ->setWorkflowOrder($workflowOrder)
            ->checkSubmit()
            ->submitOrder();

        return $this->success();
    }
}
